// pages/essay-editor.js
import {requestHeader, BASE_URL, fetchEssayTypeList, publishDemand} from '../../utils/request'
import Toast from 'tdesign-miniprogram/toast';
import { fetchServiceTypeOptions} from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    originFiles: [],
    type: 0,
    typeValue: [],
    typeName: '',
    title: '',
    content: '',
    rawContent: '',
    imageList: [],
    typeList: [],
    pickerVisible: false,
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    submitDisabled: false,
    pageLoading: false,
    gender: 0,
    chargeMode: 0,
    pay: null,
    accommodation: 0,
    remark: '',
    addressMsg: {}
  },

  handleTypePicker() {
    this.setData({ pickerVisible: true });
  },

  onColumnChange(e) {
    console.log('picker pick:', e);
  },

  onAddressSelect() {
    wx.navigateTo({
      url: `./components/address-list/index`,
    });
  },

  remarkHandle(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  onAccommodationChange(e) {
    this.setData({
      accommodation: e.detail.value
    })
  },

  payHandle(e) {
    this.setData({
      pay: e.detail.value
    })
  },

  onChargeModeChange(e) {
    this.setData({ 
      chargeMode: e.detail.value
    });
  },

  onGenderChange(e) {
    this.setData({ 
      gender: e.detail.value
    });
  },

  onTypeChange(e) {
    this.setData({ 
      type: e.detail.value
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onTitlePicker() {
    this.setData({ cityVisible: true, cityTitle: '选择城市' });
  },

  onWithoutTitlePicker() {
    this.setData({ city2Visible: true, city2Title: '' });
  },

  handleUpload(e1, e2) {
    console.log("handleUpload", e1, e2);
  },
  handleSuccess(e) {
    console.log("handleSuccess", e);
    const { files } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    console.log("handleRemove", e);
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  handleComplete(e) {
    console.log("handleComplete", e);
  },
  handleAdd(files) {
    const fileList = files.detail.files;
    const file = fileList[0];
    const self = this;
    const _imagesList = this.data.imageList;
    self.setData({
      pageLoading: true
    })
    wx.uploadFile({
      filePath: file.url,
      name: 'file',
      url: BASE_URL + "/file/upload",
      header: requestHeader(),
      success(res) {
        let r = JSON.parse(res.data)
        console.log("upload success", r.data);
        _imagesList.push(r.data);
        self.setData({
          imageList: _imagesList
        })
        Toast({
          context: self,
          selector: '#t-toast',
          message: '上传成功',
          theme: 'success'
        });
      },
      fail(res) {
        Toast({
          context: self,
          selector: '#t-toast',
          message: '上传失败，请重试',
          theme: 'error'
        });
        console.log("upload fail", res);
      },
      complete(res) {
        self.setData({
          pageLoading: false
        })
      }
    })
    console.log(this.data.imageList);
  },
  handleTitle(e) {
    console.log("handleTitle", e);
    this.setData({
      title: e.detail.value
    })
  },
  handleContent(e) {
    this.setData({
      content: e.detail.content.text,
      rawContent: e.detail.content.html
    })
    console.log("handleContent", this.data.content, this.data.rawContent);
  },

  validParam(params) {
    if (!params.addressId) {
      wx.showToast({
        title: '请选择服务地址',
      })
      return false;
    }
    if (!params.serviceTypeId) {
      wx.showToast({
        title: '请选择服务类型',
      })
      return false;
    }
    if (!params.gender && params.gender != 0) {
      wx.showToast({
        title: '请选择性别要求',
      })
      return false;
    }
    if (!params.accommodation) {
      wx.showToast({
        title: '请选择是否提供住宿',
      })
      return false;
    }
    if (!params.chargeMode) {
      wx.showToast({
        title: '请选择结算方式',
      })
      return false;
    }
    if (!params.maxSalary) {
      wx.showToast({
        title: '请填写薪资预算',
      })
      return false;
    }
    return true;
  },

  async createHandle() {
    if (this.data.submitDisabled) {
      return ;
    }
    this.setData({
      submitDisabled: true
    })
    const params = {
      serviceTypeId: this.data.type,
      chargeMode: this.data.chargeMode,
      maxSalary: this.data.pay,
      gender: this.data.gender,
      accommodation: this.data.accommodation,
      remark: this.data.remark,
      addressId: wx.getStorageSync('addressId')
    }
    console.log("createHandle params", params);
    if (this.validParam(params)) {
      const res = await publishDemand(params);
      if (res.code == 200) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '发布成功',
        });
      }
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/usercenter/my-essay/index',
        })
      }, 1000)
    }
    this.setData({
      submitDisabled: false
    })

  },

  async init() {
    const res = await fetchServiceTypeOptions();
    if (res) {
      this.setData({
        typeList: res.data
      })
    }
    // const res = await fetchEssayTypeList();
    // this.setData({
    //   typeList: res.data.map(item => {
    //     return {
    //       value: item.id,
    //       label: item.name
    //     }
    //   })
    // })
    // console.log(this.data.typeList);
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad(options) {
    this.init();
  },

  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 底部选项卡激活
    this.getTabBar().init();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})